#region "ConfigurationService"

/*
 * ####     Developer Name : Wang Yucai
 * 
 * ####     Development Tool : Microsoft VisualStudio 2010 Ultimate Edition
 * 
 * ####     Create Time : 2014-07-11 11:19:43
 * 
 * ####     Namespace : Masterduner.SourceStudio.Practices.DevelopmentLibrary.Configuration
 * 
 * ####     Type Name : ConfigurationService
 * 
 * ####     Full Name : Masterduner.SourceStudio.Practices.DevelopmentLibrary.Configuration.ConfigurationService
 * 
 * ####     Machine Name : GLCHQWYCWINW7
 * 
 * ####     UserName : GUOCOLAND/wangyucai
 * 
 * ####     CLR Version : 4.0.30319.18444
 * 
 * ####     Target Framework Version : 4.0
 */

#endregion

using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using Masterduner.SourceStudio.Practices.DevelopmentLibrary.Environments;
using Config = System.Configuration.Configuration;

namespace Masterduner.SourceStudio.Practices.DevelopmentLibrary.Configuration
{
    /// <summary>
    /// <para>Masterduner.SourceStudio.Practices.DevelopmentLibrary.Configuration.ConfigurationService</para>
    /// <para>
    /// 提供了访问配置系统的方法。
    /// </para>
    /// </summary>
    /// <remarks>
    /// <para>Target Framework Version : 4.0</para>
    /// </remarks>
    public class ConfigurationService
    {
        #region Constructor

        /// <summary>
        /// <para>构造函数：</para>
        /// <para>初始化一个<see cref="ConfigurationService" />对象实例。</para>
        /// </summary>
        public ConfigurationService()
        {
        }

        #endregion

        #region FindInCacheService
        /// <summary>
        /// 从缓存区中搜索配置对象。
        /// </summary>
        /// <typeparam name="T">缓存对象实例。</typeparam>
        /// <param name="sectionName">自定义配置节（组）名称。</param>
        /// <returns><typeparamref name="T"/>类型的缓存对象实例。</returns>
        protected virtual T FindInCacheService<T>(string sectionName)
            where T : class
        {
            object cacheData = AppDomain.CurrentDomain.GetData(sectionName);
            return cacheData.IsNull() ? null : cacheData.ForceTo<T>();
        }
        #endregion

        #region SaveInCacheService
        /// <summary>
        /// 保存<paramref name="cacheData"/>到缓存区。
        /// </summary>
        /// <param name="sectionName">用户自定义配置节（组）名称。</param>
        /// <param name="cacheData">需要缓存的数据。</param>
        protected virtual void SaveInCacheService(string sectionName, object cacheData)
        {
            AppDomain.CurrentDomain.SetData(sectionName, cacheData);
        }
        #endregion

        #region GetSection
        /// <summary>
        /// 获取<typeparamref name="TSection"/>类型的<see cref="ConfigurationSectionResult{TSection}"/>对象实例。
        /// </summary>
        /// <typeparam name="TSection">继承自<see cref="ConfigurationSection"/>的类型。</typeparam>
        /// <param name="sectionName">自定义配置节名称。</param>
        /// <returns><typeparamref name="TSection"/>类型的<see cref="ConfigurationSectionResult{TSection}"/>对象实例。</returns>
        public virtual ConfigurationSectionResult<TSection> GetSection<TSection>(string sectionName)
            where TSection : ConfigurationSection
        {
            ConfigurationSectionResult<TSection> result = this.FindInCacheService<ConfigurationSectionResult<TSection>>(sectionName);
            if (result.IsNull())
            {
                result = new ConfigurationSectionResult<TSection>(sectionName)
                {
                    ConfigurationSectionInAppConfig = this.GetSectionInAppConfig<TSection>(sectionName),
                    ConfigurationSectionInDevLibConfig = this.GetSectionInDevLibConfig<TSection>(sectionName),
                    ConfigurationSectionInUserConfig = this.GetSectionInUserConfig<TSection>(sectionName)
                };
                this.SaveInCacheService(sectionName, result);
            }
            return result;
        }
        #endregion

        #region GetSectionGroup
        /// <summary>
        /// 获取<typeparamref name="TSectionGroup"/>类型的<see cref="ConfigurationSectionGroupResult{T}"/>对象实例。
        /// </summary>
        /// <typeparam name="TSectionGroup">配置节组类型。</typeparam>
        /// <param name="sectionGroupName">配置节组名称。</param>
        /// <returns><typeparamref name="TSectionGroup"/>类型的<see cref="ConfigurationSectionGroupResult{T}"/>对象实例。</returns>
        public virtual ConfigurationSectionGroupResult<TSectionGroup> GetSectionGroup<TSectionGroup>(string sectionGroupName)
            where TSectionGroup : ConfigurationSectionGroup
        {
            ConfigurationSectionGroupResult<TSectionGroup> result = this.FindInCacheService<ConfigurationSectionGroupResult<TSectionGroup>>(sectionGroupName);
            if (result.IsNull())
            {
                result = new ConfigurationSectionGroupResult<TSectionGroup>(sectionGroupName)
                {
                    ConfigurationSectionGroupInAppConfig = this.GetSectionGroupInAppConfig<TSectionGroup>(sectionGroupName),
                    ConfigurationSectionGroupInDevLibConfig = this.GetSectionGroupInDevLibConfig<TSectionGroup>(sectionGroupName),
                    ConfigurationSectionGroupInUserConfig = this.GetSectionGroupInUserConfig<TSectionGroup>(sectionGroupName)
                };
                this.SaveInCacheService(sectionGroupName, result);
            }
            return result;
        }
        #endregion

        #region GetAppConfiguration
        /// <summary>
        /// 获取app.config中的配置对象。
        /// </summary>
        /// <returns><see cref="System.Configuration.Configuration"/>对象实例。</returns>
        public virtual Config GetAppConfiguration()
        {
            Debug.WriteLine("ConfigurationService::GetAppConfiguration::start to load app.config configuration file!");
            return ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        }
        #endregion

        #region GetSectionInAppConfig
        /// <summary>
        /// 获取app.config配置文件中的用户自定义配置。
        /// </summary>
        /// <typeparam name="TSection">继承自<see cref="ConfigurationSection"/>的类型。</typeparam>
        /// <param name="sectionName">自定义配置节名称。</param>
        /// <returns><typeparamref name="TSection"/>类型的<see cref="ConfigurationSection"/>对象实例。</returns>
        public virtual TSection GetSectionInAppConfig<TSection>(string sectionName)
            where TSection : ConfigurationSection
        {
            try
            {
                Config configuration = this.GetAppConfiguration();
                ConfigurationSection section = configuration.Sections[sectionName];
                return section.IsNull() ? null : section.ForceTo<TSection>();
            }
            catch
            {
                return null;
            }
        }
        #endregion

        #region GetSectionGroupInAppConfig
        /// <summary>
        /// 从app.config中获取名称为<paramref name="sectionGroupName"/>的配置节组。
        /// </summary>
        /// <typeparam name="TSectionGroup">继承自<see cref="ConfigurationSectionGroup"/>的类型。</typeparam>
        /// <param name="sectionGroupName">配置节组名称。</param>
        /// <returns><typeparamref name="TSectionGroup"/>配置节组对象实例。</returns>
        public virtual TSectionGroup GetSectionGroupInAppConfig<TSectionGroup>(string sectionGroupName)
            where TSectionGroup : ConfigurationSectionGroup
        {
            try
            {
                Config configuration = this.GetAppConfiguration();
                ConfigurationSectionGroup sectionGroup = configuration.SectionGroups[sectionGroupName];
                return sectionGroup.IsNull() ? null : sectionGroup.ForceTo<TSectionGroup>();
            }
            catch
            {
                return null;
            }
        }
        #endregion

        #region GetDevLibConfigurationFileInfo
        /// <summary>
        /// 获取开发库默认配置文件信息。
        /// </summary>
        /// <returns><see cref="FileInfo"/>对象实例。</returns>
        protected virtual FileInfo GetDevLibConfigurationFileInfo()
        {
            if (!DevelopmentLibraryEnvironment.CurrentEnvironment.DevelopmentLibraryDirectoryNotFound)
            {
                DirectoryInfo directoryInfo = DevelopmentLibraryEnvironment.CurrentEnvironment.FinalLoadPath;
                return new FileInfo(Path.Combine(directoryInfo.FullName, DevelopmentLibraryFolders.Configs.ToString(), DevelopmentLibraryEnvironment.DefaultConfigurationFileName));
            }
            else return null;
        }
        #endregion

        #region GetDevLibConfiguration
        /// <summary>
        /// 获取开发库默认配置文件中的配置对象。
        /// </summary>
        /// <returns><see cref="System.Configuration.Configuration"/>对象实例。</returns>
        public virtual Config GetDevLibConfiguration()
        {
            Debug.WriteLine("ConfigurationService::GetDevLibConfiguration::start to load DevLib's default configuration file!");
            FileInfo configurationFileInfo = this.GetDevLibConfigurationFileInfo();
            if (configurationFileInfo.IsNull() || !configurationFileInfo.Exists)
            {
                Debug.WriteLine("ConfigurationService::GetDevLibConfiguration::{0}", configurationFileInfo.NotIsNull() ? configurationFileInfo.FullName : "configuration fileinfo is null");
                return null;
            }
            else
            {
                ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap() { ExeConfigFilename = configurationFileInfo.FullName };
                return ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            }
        }
        #endregion

        #region GetSectionInDevLibConfig
        /// <summary>
        /// 从开发库默认配置文件中获取名称为<paramref name="sectionName"/>的配置节。
        /// </summary>
        /// <typeparam name="TSection">继承自<see cref="ConfigurationSection"/>的<typeparamref name="TSection"/>类型对象实例。</typeparam>
        /// <param name="sectionName">配置节名称。</param>
        /// <returns><typeparamref name="TSection"/>配置节对象实例。</returns>
        public virtual TSection GetSectionInDevLibConfig<TSection>(string sectionName)
            where TSection : ConfigurationSection
        {
            try
            {
                Config configuration = this.GetDevLibConfiguration();
                if (configuration.IsNull())
                {
                    return null;
                }
                else
                {
                    ConfigurationSection section = configuration.Sections[sectionName];
                    return sectionName.IsNull() ? null : sectionName.ForceTo<TSection>();
                }
            }
            catch
            {
                return null;
            }
        }
        #endregion

        #region GetSectionGroupInDevLibConfig
        /// <summary>
        /// 从开发库默认配置文件中搜索名称为<paramref name="sectionGroupName"/>的配置节组。
        /// </summary>
        /// <typeparam name="TSectionGroup">继承自<see cref="ConfigurationSectionGroup"/>的类型。</typeparam>
        /// <param name="sectionGroupName">配置节组名称。</param>
        /// <returns><typeparamref name="TSectionGroup"/>配置节组对象实例。</returns>
        public virtual TSectionGroup GetSectionGroupInDevLibConfig<TSectionGroup>(string sectionGroupName)
            where TSectionGroup : ConfigurationSectionGroup
        {
            try
            {
                Config configuration = this.GetDevLibConfiguration();
                if (configuration.IsNull())
                {
                    return null;
                }
                else
                {
                    ConfigurationSectionGroup sectionGroup = configuration.SectionGroups[sectionGroupName];
                    return sectionGroup.IsNull() ? null : sectionGroup.ForceTo<TSectionGroup>();
                }
            }
            catch
            {
                return null;
            }
        }
        #endregion

        #region GetUserConfiguration
        /// <summary>
        /// 从用户自定义配置文件中加载配置。
        /// </summary>
        /// <param name="sectionName">配置节（组）名称。</param>
        /// <param name="isSectionGroup">是否为配置节组。</param>
        /// <returns><see cref="System.Configuration.Configuration"/>对象实例。</returns>
        public virtual Config GetUserConfiguration(string sectionName, bool isSectionGroup = false)
        {
            Debug.WriteLine("ConfigurationService::GetUserConfiguration::start to load user configuration file!");
            UserCustomizedConfigurationManager manager = new UserCustomizedConfigurationManager(sectionName, isSectionGroup);
            if (manager.HasUserCustomizedConfiguration && manager.UserConfigurationFile.Exists)
            {
                Debug.WriteLine("ConfigurationService::GetUserConfiguration::{0}", manager.UserConfigurationFile.FullName);
                ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap() { ExeConfigFilename = manager.UserConfigurationFile.FullName };
                return ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            }
            else
            {
                Debug.WriteLine("ConfigurationService::GetUserConfiguration::user configuration file not exists!");
                return null;
            }
        }
        #endregion

        #region GetSectionInUserConfig
        /// <summary>
        /// 从用户自定配置文件中获取名称为<paramref name="sectionName"/>的配置。
        /// </summary>
        /// <typeparam name="TSection">继承自<see cref="ConfigurationSection"/>的类型。</typeparam>
        /// <param name="sectionName">配置节名称。</param>
        /// <returns><typeparamref name="TSection"/>类型的配置对象实例。</returns>
        public virtual TSection GetSectionInUserConfig<TSection>(string sectionName)
            where TSection : ConfigurationSection
        {
            try
            {
                Config configuration = this.GetUserConfiguration(sectionName);
                if (configuration.IsNull())
                {
                    return null;
                }
                else
                {
                    ConfigurationSection section = configuration.Sections[sectionName];
                    return section.IsNull() ? null : section.ForceTo<TSection>();
                }
            }
            catch
            {
                return null;
            }
        }
        #endregion

        #region GetSectionGroupInUserConfig
        /// <summary>
        /// 从用户自定义配置文件中获取名称为<paramref name="sectionGroupName"/>的配置节组对象实例。
        /// </summary>
        /// <typeparam name="TSectionGroup">继承自<see cref="ConfigurationSectionGroup"/>的类型。</typeparam>
        /// <param name="sectionGroupName">配置节组名称。</param>
        /// <returns><typeparamref name="TSectionGroup"/>类型的配置节组对象实例。</returns>
        public virtual TSectionGroup GetSectionGroupInUserConfig<TSectionGroup>(string sectionGroupName)
            where TSectionGroup : ConfigurationSectionGroup
        {
            try
            {
                Config configuration = this.GetUserConfiguration(sectionGroupName, true);
                if (configuration.IsNull())
                {
                    return null;
                }
                else
                {
                    ConfigurationSectionGroup sectionGroup = configuration.SectionGroups[sectionGroupName];
                    return sectionGroup.IsNull() ? null : sectionGroup.ForceTo<TSectionGroup>();
                }
            }
            catch
            {
                return null;
            }
        }
        #endregion
    }
}

#region README

/*
 * ####     ©2014 Wang Yucai
 * 
 * ####     Contact me
 *                  
 *                  E-mail : Masterduner@Yeah.net
 *                  Mobile : 13621384677
 *                  QQ : 180261899
 */

#endregion